<template>
  <div class="app-container">
    <el-row :gutter="50">
      <!--用户数据-->
      <el-col :span="50" :xs="24" style="width: 100%"
        ><!--style="border: 1px solid red"-->
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="作品标题" prop="vTitle">
            <el-input
              v-model="queryParams.vTitle"
              placeholder="请输入作品标题"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="queryParams.email"
              placeholder="请输入用户邮箱"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
              disabled
            />
          </el-form-item>
          <el-form-item label="状态" prop="vState">
            <el-select
              v-model="queryParams.vState"
              placeholder="用户状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
              disabled
              >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
              >导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="listVotes"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="voteList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <!-- <el-table-column
            label="作品编号"
            align="center"
            key="id"
            prop="id"
            v-if="columns[0].visible"
            width="120"
          /> -->
          <!-- <el-table-column
            label="作品标题"
            align="center"
            key="vTitle"
            prop="vTitle"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
            width="120"
          /> -->
          <el-table-column
            label="视频封面"
            align="center"
            key="vCover"
            prop="vCover"
            v-if="columns[0].visible"
            width="120"
          >
            <template slot-scope="scope">
              <img
                :src="scope.row.vCover"
                alt="封面"
                style="width: 50px; height: 50px"
              />
            </template>
          </el-table-column>

          <el-table-column
            label="拜年视频"
            align="center"
            key="vUrl"
            prop="vUrl"
            v-if="columns[5].visible"
            width="220"
          >
            <template slot-scope="scope">
              <!-- 视频 -->
              <video
                class="vote-video"
                :src="scope.row.vUrl"
                controls
                mode="widthFix"
                :poster="scope.row.vCover"
              ></video>
            </template>
          </el-table-column>

          <el-table-column
            label="作者昵称"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[1].visible"
            width="120"
          />
          <!--           <el-table-column
            label="作者邮箱"
            align="center"
            key="email"
            prop="email"
            v-if="columns[2].visible"
            width="120"
          /> -->
          <!--   <el-table-column
            label="作品状态"
            align="center"
            key="vCount"
            v-if="columns[5].visible"
            width="120"
          > -->
          <!-- 列内容的插槽 -->
          <!--    <template slot-scope="scope">
              {{ scope.row.vState }}
            </template>
          </el-table-column> -->
          <el-table-column
            label="拜年内容"
            align="center"
            key="vDesc"
            prop="vDesc"
            v-if="columns[2].visible"
            width="420"
          />

          <el-table-column
            label="作品状态"
            align="center"
            key="vState"
            v-if="columns[3].visible"
            width="120"
          >
            <template slot-scope="scope">
              <!-- 去掉 只有两个选项 -->
              <!-- <el-switch
                v-model="scope.row.vState"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch> -->
              <!-- 改用选项卡 因为有3个选项 -->
              <select
                v-model="selectedValues[scope.$index]"
                ref="mySelect"
                @change="handleStatusChange(scope.row, selectedValues[scope.$index])"
              >
                <option value="0">不显示</option>
                <option value="1">视频区拜年</option>
                <option value="2">首页拜年</option>
              </select>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            v-if="columns[4].visible"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="260"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
                >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="listVotes"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者昵称" prop="nickName">
              <el-input
                v-model="form.nickName"
                placeholder="请输入用户昵称"
                maxlength="30"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作品标题" prop="nickName">
              <el-input
                v-model="form.vTitle"
                placeholder="请输入作品标题"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作品票数" prop="phonenumber">
              <el-input
                v-model="form.vCount"
                placeholder="请输入作品票数"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="form.id == undefined"
              label="作品标题"
              prop="vTitle"
            >
              <el-input
                v-model="form.vTitle"
                placeholder="请输入作品标题"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="form.id == undefined"
              label="用户密码"
              prop="password"
            >
              <el-input
                v-model="form.password"
                placeholder="请输入用户密码"
                type="password"
                maxlength="20"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row> </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="作品简介">
              <el-input
                v-model="form.vDesc"
                type="textarea"
                placeholder="简单介绍下作品吧"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { delVote, getVote, listVote, updateVoteById } from "@/api/web/vote";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect },
  data() {
    return {
      // 下拉选项的值
      // selectedValue: "0",
      selectedValues: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 作品的数据
      voteList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vTitle: undefined,
        email: undefined,
        vState: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `作品编号`, visible: true },
        { key: 1, label: `作品标题`, visible: true },
        { key: 2, label: `作品封面`, visible: true },
        { key: 3, label: `作者昵称`, visible: true },
        { key: 4, label: `作者邮箱`, visible: true },
        { key: 5, label: `作品票数`, visible: true },
        { key: 6, label: `作品简介`, visible: true },
        { key: 7, label: `作品状态`, visible: true },
        { key: 8, label: `创建时间`, visible: true },
      ],
      // 表单校验
      rules: {
        vTitle: [
          { required: true, message: "作品标题不能为空", trigger: "blur" },
          {
            min: 10,
            max: 50,
            message: "作品标题长度必须介于 10 和 50 之间",
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      // 下拉框 状态选择
      options: [
        {
          value: "0",
          label: "不显示",
        },
        {
          value: "1",
          label: "征集视频",
        },
        {
          value: "2",
          label: "嘉宾视频",
        },
      ],
      // 下拉框选项的值
      value: "",
      // 其他的
    };
  },
  created() {
    this.listVotes(); //查询
  },

  methods: {
    /** 查询投票作品列表 */
    listVotes() {
      this.loading = true;

      listVote(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.voteList = response.rows;
          this.total = response.total;
          this.loading = false;
          console.log(response.rows);
          response.rows.forEach(item => {
           this.selectedValues.push(item.vState);
          });
          console.log(this.selectedValues);
        }
      );
    },
    // 用户状态修改
    handleStatusChange(row, choice) {
      // const choice = this.selectedValue;
      console.log("choice的值", choice);
      //  显示内容
      const text =
        choice == 1
          ? "展示在视频拜年区"
          : choice == 2
          ? "展示在首页拜年区"
          : "不显示";

      this.$modal
        .confirm('"' + row.nickName + '"' + '的作品将"' + text + '" ')
        .then(function () {
          // 将改变的值给了源对象
          row.vState = choice;
          //返回该对象
          console.log("打印修改的对象");
          console.log(row);
          return updateVoteById(row);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.vState = row.vState === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        vTitle: undefined,
        nickName: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        vState: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.listVotes();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加作品";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      console.log(row);

      const id = row.id;

      getVote(id).then((response) => {
        this.form = response.rows[0];
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          //修改
          updateVoteById(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.listVotes();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id;
      this.$modal
        .confirm('是否确认删除编号为"' + userIds + '"的作品数据？')
        .then(function () {
          //删除vote
          return delVote(userIds);
        })
        .then(() => {
          this.listVotes();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.listVotes();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //数字处理
    formattedNumber(number) {
      if (number >= 10000) {
        // 数字大于等于10000时显示为x.x万
        return (number / 10000).toFixed(1) + "万";
      } else if (number >= 1000) {
        // 数字大于等于1000时显示为x千
        return parseInt(number / 1000) + "千";
      } else {
        return number.toString(); // 小于1000的数字直接显示
      }
    },
  },
};
</script>
<style scoped>
.vote-video {
  width: 200px;
  height: 200px;
}
</style>
